<template>
  <div class="comment-sys-page">
    <el-card>
      <table-bar :show-top="true" :show-bottom="false" @search="search" @reset="clear">
        <template #top>
          <el-form :inline="true" :model="formInline" class="form-search">
            <el-form-item label="商家名称">
              <el-input
                v-model="formInline.shopName"
                maxlength="50"
                placeholder="请输入商家名称"
                clearable
              />
            </el-form-item>
            <el-form-item label="商家编码">
              <el-input
                v-model="formInline.shopCode"
                maxlength="30"
                placeholder="请输入商家编码"
                clearable
              />
            </el-form-item>
            <el-form-item label="商品ID">
              <el-input
                v-model="formInline.productId"
                type="number"
                placeholder="请输入商品ID"
                clearable
              />
            </el-form-item>
            <el-form-item label="评论内容">
              <el-input
                v-model="formInline.keyword"
                maxlength="30"
                placeholder="请输入评论内容"
                clearable
              />
            </el-form-item>
            <el-form-item label="敏感词审核">
              <el-select
                v-model="formInline.ifSensitive"
                placeholder="请选择状态"
                clearable
                style="width: 120px"
              >
                <el-option label="已审核" value="1" />
                <el-option label="未审核" value="0" />
              </el-select>
            </el-form-item>
          </el-form>
        </template>
      </table-bar>

      <art-table
        :data="tableData"
        :loading="tableLoading"
        :border="true"
        :total="total"
        :current-page="formInline.page"
        :page-size="formInline.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :show-header-background="true"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="shopName" label="商家名称" min-width="150" />
        <el-table-column prop="shopCode" label="商家编码" min-width="150" />
        <el-table-column prop="productId" label="商品ID" min-width="120" align="center" />
        <el-table-column prop="name" label="评论人" min-width="120" />
        <el-table-column prop="createTime" label="评论日期" min-width="180" />
        <el-table-column label="操作" width="250" align="center">
          <template #default="scope">
            <button-table type="view" text="查看" @click="view(scope.row)" />
            <button-table
              :type="scope.row.state === 1 ? 'delete' : 'success'"
              @click="changeCommentState(scope.row)"
              :text="scope.row.state === 1 ? '屏蔽' : '展示'"
            />
            <el-popconfirm title="确定删除该评论吗？" @confirm="handleDelete(scope.row)">
              <template #reference>
                <button-table type="delete" text="删除" />
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </art-table>
    </el-card>

    <!-- 评论详情对话框 -->
    <el-dialog
      v-model="dialogVisible.view"
      title="评论详情"
      width="50%"
      :close-on-click-modal="false"
    >
      <div class="comment-detail">
        <div class="detail-item">
          <span class="detail-label">评论用户：</span>
          <span class="detail-value">{{ commentDetail.name || '未知用户' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">评论时间：</span>
          <span class="detail-value">{{ commentDetail.createTime }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">评论内容：</span>
          <div class="detail-value content-detail">{{ commentDetail.comment }}</div>
        </div>
        <div class="detail-item" v-if="commentDetail.addComment">
          <span class="detail-label">追加评论：</span>
          <div class="detail-value content-detail">{{ commentDetail.addComment }}</div>
        </div>
        <div class="detail-item" v-if="commentDetail.sensitiveWord">
          <span class="detail-label">敏感词：</span>
          <span class="detail-value">{{ commentDetail.sensitiveWord }}</span>
        </div>
        <div class="detail-item" v-if="commentDetail.images && commentDetail.images.length > 0">
          <span class="detail-label">评论图片：</span>
          <div class="detail-value">
            <img
              v-for="(img, index) in commentDetail.images"
              :key="index"
              :src="img"
              class="comment-image"
            />
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible.view = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import {
    commentSysGetall,
    commentSysGetById,
    commentSysUpdate,
    commentSysDelete
  } from '@/api/commentApi'
  import {
    CommentGetAllParam,
    CommentUpdateParam,
    ShopComment,
    CommentDetail
  } from '@/api/model/commentModel'
  import { ApiStatus } from '@/utils/http/status'
  import ArtTable from '@/components/Table/ArtTable.vue'
  import TableBar from '@/components/Table/TableBar.vue'
  import ButtonTable from '@/components/Form/ButtonTable.vue'

  let formInline = ref<CommentGetAllParam>({
    page: 1,
    pageSize: 10,
    shopName: '',
    shopCode: '',
    productId: undefined,
    keyword: '',
    ifSensitive: undefined
  })
  let tableLoading = ref(false)
  let dialogVisible = ref({
    view: false
  })
  let total = ref(0)
  let tableData = ref<ShopComment[]>([])
  let commentDetail = ref<CommentDetail>({
    commentId: 0,
    image: '',
    addImage: '',
    comment: '',
    addComment: '',
    images: [],
    addImages: [],
    sensitiveWord: '',
    time: '',
    createTime: '',
    addTime: '',
    name: ''
  })

  onMounted(() => {
    getAll(formInline.value)
  })

  // 获取所有评论
  async function getAll(params: CommentGetAllParam) {
    try {
      tableLoading.value = true
      // 确保传递的参数符合后端要求
      const requestData: any = {
        page: params.page,
        pageSize: params.pageSize,
        keyword: params.keyword, //关键词
        ifSensitive: params.ifSensitive, // 是否敏感词审核
        shopName: params.shopName,
        shopCode: params.shopCode,
        productId: params.productId
      }

      // 移除值为 undefined 的字段
      Object.keys(requestData).forEach((key) => {
        if (requestData[key] === undefined) {
          delete requestData[key]
        }
      })

      const res = await commentSysGetall(requestData as CommentGetAllParam)
      if (res.code === ApiStatus.success) {
        tableData.value = res.data?.list || []
        total.value = res.data?.total || 0
      }
    } catch (error) {
      console.error('获取评论列表失败:', error)
      ElMessage.error('获取评论列表失败')
    } finally {
      tableLoading.value = false
    }
  }

  // 分页大小变化
  function handleSizeChange(val: number) {
    formInline.value.pageSize = val
    getAll(formInline.value)
  }

  // 当前页码变化
  function handleCurrentChange(val: number) {
    formInline.value.page = val
    getAll(formInline.value)
  }

  // 搜索
  function search() {
    total.value = 0
    formInline.value.page = 1
    // 确保 productId 为空字符串时转换为 undefined
    if (formInline.value.productId === '') {
      formInline.value.productId = undefined
    }
    getAll(formInline.value)
  }

  // 重置
  function clear() {
    formInline.value = {
      page: 1,
      pageSize: 10,
      shopName: '',
      shopCode: '',
      productId: undefined,
      keyword: '',
      ifSensitive: 0
    }
    getAll(formInline.value)
  }

  // 查看评论详情
  async function view(row: ShopComment) {
    try {
      tableLoading.value = true
      const res = await commentSysGetById({ commentId: row.commentId })
      if (res.code === ApiStatus.success) {
        commentDetail.value = res.data
        dialogVisible.value.view = true
      }
    } catch (error) {
      console.error('获取评论详情失败:', error)
      ElMessage.error('获取评论详情失败')
    } finally {
      tableLoading.value = false
    }
  }

  // 改变评论状态
  async function changeCommentState(row: ShopComment) {
    const newState = row.state === 1 ? 0 : 1
    const confirmText = newState === 0 ? '屏蔽' : '展示'

    try {
      await ElMessageBox.confirm(`确定要${confirmText}此评论吗？`, '确认操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })

      tableLoading.value = true
      const updateParam: CommentUpdateParam = {
        commentId: row.commentId,
        state: newState
      }
      const res = await commentSysUpdate(updateParam)

      if (res.code === ApiStatus.success) {
        ElMessage.success(`${confirmText}成功`)
        await getAll(formInline.value)
      } else {
        ElMessage.error(res.message || `${confirmText}失败`)
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error(`${confirmText}评论失败:`, error)
        ElMessage.error(`${confirmText}评论失败`)
      }
    } finally {
      tableLoading.value = false
    }
  }

  // 删除评论
  async function handleDelete(row: ShopComment) {
    try {
      tableLoading.value = true
      const deleteParam = {
        commentId: row.commentId
      }
      const res = await commentSysDelete(deleteParam)

      if (res.code === ApiStatus.success) {
        ElMessage.success('删除成功')
        await getAll(formInline.value)
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      console.error('删除评论失败:', error)
      ElMessage.error('删除评论失败')
    } finally {
      tableLoading.value = false
    }
  }
</script>

<style lang="scss" scoped>
  .comment-sys-page {
    padding: 20px;

    .form-search {
      margin-bottom: 15px;
    }

    .content-text {
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
    }

    .comment-detail {
      .detail-item {
        display: flex;
        margin-bottom: 15px;

        .detail-label {
          flex-shrink: 0;
          width: 100px;
          font-size: 14px;
          color: #606266;
        }

        .detail-value {
          flex: 1;
          font-size: 14px;
          color: #303133;
        }

        .content-detail {
          line-height: 1.6;
          word-break: break-word;
          white-space: pre-wrap;
        }

        .comment-image {
          max-width: 100px;
          max-height: 100px;
          margin-right: 10px;
          border-radius: 4px;
        }
      }
    }

    // 响应式设计
    @media screen and (max-width: $device-phone) {
      padding: 10px;

      .form-search {
        .el-form-item {
          width: 100%;
          margin-bottom: 10px;

          .el-input,
          .el-select {
            width: 100%;
          }
        }
      }

      .comment-detail {
        .detail-item {
          flex-direction: column;

          .detail-label {
            width: 100%;
            margin-bottom: 5px;
          }
        }
      }

      .el-dialog {
        width: 90% !important;
      }
    }
  }
</style>
